﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Core;
using System.Diagnostics;

namespace Silvermoon.Windows
{
    public class UITimer : IDisposable
    {
        private bool isRunning;
        private int startTick;

        public UITimer()
            : base()
        {
            Repeated = true;
        }

        public void Dispose()
        {
            Stop();
            GC.SuppressFinalize(this);
        }

        ~UITimer()
        {
            Dispose();
        }

        public int Interval { get; set; }

        /// <summary>
        /// True to continuously tick, false to tick only once.
        /// </summary>
        public bool Repeated { get; set; }

        public bool Enabled
        {
            get { return isRunning; }
            set
            {
                if (value & !isRunning) Start();
                if (!value & isRunning) Stop();
            }
        }

        public event EventHandler Tick;

        public bool IsRunning { get { return isRunning; } }

        public void Start()
        {
            if (!isRunning)
            {
                isRunning = true;
                startTick = Environment.TickCount;
                Screen s = Screen.Current;
                if (s != null) s.Tick += OnTimerTick;
            }
        }

        public void Restart()
        {
            Stop();
            Start();
        }


        public void Stop()
        {
            if (isRunning)
            {
                Screen screen = Screen.Current;
                if (screen != null) screen.Tick -= OnTimerTick;
                isRunning = false;
            }
        }

        private void OnTimerTick(object sender, TimeEventArgs e)
        {
            int t = e.Tick;
            int duration = t - startTick;
            if (duration >= Interval)
            {
                startTick = t;
                if (!Repeated) Stop();
                OnTick();
            }
        }

        protected virtual void OnTick()
        {
            if (Tick != null) Tick(this, EventArgs.Empty);
        }

    }
}
